package com.hyjoy.service.impl;

import com.hyjoy.constant.Constant;
import com.hyjoy.dao.CategoryDao;
import com.hyjoy.dao.impl.CategoryDaoImpl;
import com.hyjoy.entity.Category;
import com.hyjoy.service.CategoryService;
import com.hyjoy.util.BeanFactory;
import com.hyjoy.util.JedisUtils;
import com.hyjoy.util.JsonUtil;
import redis.clients.jedis.Jedis;

import java.util.List;

public class CategoryServiceImpl implements CategoryService {

    @Override
    /**
     * 查询所有分类
     */
    public String findAll() throws Exception {
        //1.调用dao 查询所有分类
        CategoryDao cd = new CategoryDaoImpl();
        List<Category> list = cd.findAll();

        //2.将list转换成json字符串
        if (list != null && list.size() > 0) {
            return JsonUtil.list2json(list);
        }
        return null;
    }

    @Override
    /**
     * 从redis中获取所有的分类
     */
    public String findAllFromRedis() throws Exception {
        //1.获取jedis
        Jedis jedis = JedisUtils.getJedis();

        //2.从redis中获取数据
        String value = jedis.get(Constant.STORE_CATEGORY_LIST);

        //3.判断数据是否为空
        if (value == null) {
            //3.1若为空 ,调用findAll() 将查询的结果放入redis return
            value = findAll();

            jedis.set(Constant.STORE_CATEGORY_LIST, value);
            System.out.println("从mysql中获取");
            return value;
        }
        //3.2若不为空,return
        System.out.println("从redis中获取");

        return value;
    }

    @Override
    public List<Category> findList() throws Exception {
        CategoryDao cd = new CategoryDaoImpl();
        return cd.findAll();
    }

    @Override
    public void save(Category c) throws Exception {
        //1.调用dao 完成添加
        CategoryDao cd = new CategoryDaoImpl();
        cd.save(c);

        //2.更新redis
        Jedis j = null;
        try {
            j = JedisUtils.getJedis();
            //清除redis中数据
            j.del(Constant.STORE_CATEGORY_LIST);
        } finally {
            JedisUtils.closeJedis(j);
        }
    }

}